package com.longrise.android.byjk.widget.recyclerviewadapter;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

/**
 * Created by sjz on 15/4/21.
 * 配置visibleThreshold > 0 无缝隙加载
 * 该判断方式较为极端
 */
public abstract class RecyclerOnScrollListener extends RecyclerView.OnScrollListener {

    private int previousTotal = 0; // The total number of items in the dataset after the last load
    private boolean loading = true; // True if we are still waiting for the last set of data to load.
    private int visibleThreshold = 3; //default == 3 The minimum amount of items to have below your current scroll position before loading more.
    int firstVisibleItem, visibleItemCount, totalItemCount;
    int lastVisiableItem;

    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);
        LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
        // fix RecyclerView can not scroll in SwipeRefreshLayout
        onScrollStatus(linearLayoutManager.findFirstCompletelyVisibleItemPosition() == 0);

        visibleItemCount = recyclerView.getChildCount();
        totalItemCount = linearLayoutManager.getItemCount();
        firstVisibleItem = linearLayoutManager.findFirstVisibleItemPosition();
        lastVisiableItem = linearLayoutManager.findLastVisibleItemPosition();

        if (loading) {
            if (totalItemCount > previousTotal) {
                loading = false;
                previousTotal = totalItemCount;
            }
        }
        if (!loading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
            onLoadListener();
            loading = true;
        }
    }

    public void reset() {
        previousTotal = 0;
        loading = true;
    }

    public abstract void onLoadListener();

    public abstract void onScrollStatus(boolean enable);
}
